<template>
  <div class="infinite-container">
    <select-role3 @familychang="selperson" ref="childRole"></select-role3>
    <div class="warning-tips" @click="go()">如信息有误，点击去完善信息>></div>
    <mu-list class="bgwhite">
      <mu-list-item title="就诊人">
        <mu-text-field
          hintText="请输入真实姓名"
          inputClass="text-right"
          hintTextClass="text-right"
          v-model="form.realName"
          slot="right"
          class="mt15"
          disabled
        ></mu-text-field>
      </mu-list-item>
      <mu-divider />

      <mu-list-item title="证件号码">
        <div slot="right" class="mt15 text-right" style="color: rgba(0, 0, 0, .87)">{{idCard}}</div>
        <!-- <mu-text-field
          v-model="idCard"
          slot="right"
          type="text"
          class="mt15"
          hintText="请输入证件号码"
          inputClass="text-right"
          hintTextClass="text-right"
          disabled
        ></mu-text-field> -->
      </mu-list-item>
      <mu-divider />

      <mu-list-item title="出生日期">
        <!-- <mu-date-picker
          v-model="bornDate"
          slot="right"
          hintText="请选择出生日期"
          inputClass="text-right"
          hintTextClass="text-right"
        ></mu-date-picker> -->
        <!-- <span slot="right" @click="showDatePicker">{{bornDate || '请选择日期'}}</span> -->
        <span slot="right">{{(bornDate || '') | format}}</span>
      </mu-list-item>
      <mu-divider />

      <mu-list-item title="性别">
        <span class="list-right-title">
          <selector :options="SEX_TYPE" @selectchange="handleSexChange" :defaultValue="sex" disabled></selector>
        </span>
      </mu-list-item>
      <mu-divider />

      <mu-list-item title="手机号">
        <div slot="right">
          <mu-text-field
            style="width:100px;"
            hintTextClass="text-right"
            :value="form.phoneNumber | hideMobile"
            disabled
            slot="right"
            class="mt10"
            inputClass="text-right"
          ></mu-text-field>
          <mu-raised-button
            class="small no-shadow"
            :label="vcodeLabel"
            @click="getVcode"
            secondary
            :disabled="vcodeDisabled"
          ></mu-raised-button>
        </div>
      </mu-list-item>
      <mu-divider />
      <mu-list-item title="验证码">
        <div slot="right">
          <mu-text-field
            hintTextClass="text-right"
            hintText="请输入验证码"
            v-model="vcode"
            style="width:110px;"
            class="mt10"
            inputClass="text-right"
          ></mu-text-field>
        </div>
      </mu-list-item>
      
      <mu-list-item class="tcenter" @click="showGuardian = true" v-if="!showGuardian">
        <img class="zxjd" src="../../assets/images/zxjd_icon_add.png"/>
        添加监护人
      </mu-list-item>
    </mu-list>

    <mu-list class="bgwhite mt10" v-if="showGuardian">
      <mu-list-item title="监护人姓名" @click="$refs.childRole.show()">
        <div slot="right">{{guardian.realname}}<i class="iconfont icon-small-arrow-right t3 v-middle"></i></div>
      </mu-list-item>
      <mu-divider />
      <mu-list-item title="监护人证件类型">
        <span class="list-right-title">
          <selector
            :options="CARD_TYPE"
            @selectchange="handleCardChange"
            :defaultValue="guardian.cardtype"
          ></selector>
        </span>
      </mu-list-item>
      <mu-divider />
      <mu-list-item title="监护人证件号码">
        <mu-text-field
          v-model="guardian.idcard"
          slot="right"
          type="text"
          class="mt15"
          hintText="请输入证件号码"
          inputClass="text-right"
          hintTextClass="text-right"
        ></mu-text-field>
      </mu-list-item>
      <mu-divider />
      <mu-list-item title="监护人手机号">
        <mu-text-field
          v-model="guardian.mobile"
          type="number"
          slot="right"
          class="mt15"
          hintText="请输入手机号码"
          inputClass="text-right"
          hintTextClass="text-right"
        ></mu-text-field>
      </mu-list-item>
      <mu-list-item class="tcenter" @click="showGuardian = false" v-if="age > 6">
        <img class="zxjd" src="../../assets/images/zxjd_icon_qxtj.png"/>
        取消添加监护人
      </mu-list-item>
    </mu-list>

    <div class="pd10 color-info">
      未成年人等无民事行为能力和限制民事行为能力的人群，须添加 监护人信息
    </div>

    <mu-flexbox :gutter="0" style="margin-top:2.5em;" >
      <mu-flexbox-item grow="1">
        <mu-raised-button
          class="submit-btn"
          :class="[loginDisabled ? 'disabled' : '']"
          label="确认"
          fullWidth
          primary
          @click="checkCode"
        ></mu-raised-button>
      </mu-flexbox-item>
    </mu-flexbox>

    <!--  dialogMobiles -->
    <mu-dialog :open="dialogMobiles" title="请选择手机号">
      <div class>
        <div class="cards-wrapper">
          <mu-list>
            <mu-list-item
              v-for="(v, i) in mobilesList"
              :key="i"
              @click.native="mobileSelectHandle(v)"
            >
              <div>{{v.phone}}</div>
              <i class="iconfont icon-small-arrow-right" slot="right" />
            </mu-list-item>
          </mu-list>
        </div>
      </div>
    </mu-dialog>
    <!-- confirm dialog -->
    <mu-dialog :open="selectCardDialog" title="请选择需要绑定的卡片(可多选)">
      <div class>
        <div class="cards-wrapper">
          <mu-list>
            <mu-list-item
              :describeText="v.patientMedicalCardNumber"
              v-for="(v, i) in listMedicalCard"
              :key="i"
            >
              <div slot="title">
                {{HIS_CARD_TYPE[v.patientMedicalCardType]}} &nbsp;
                <small
                  class="color-price"
                >{{v.patientMedicalCardName}}</small>
              </div>
              <div slot="right">
                <mu-checkbox :nativeValue="v.patientMedicalCardNumber" v-model="checklist" />
              </div>
            </mu-list-item>
          </mu-list>
        </div>
      </div>
      <mu-flat-button slot="actions" @click="selectCardDialog=false" label="取消" />
      <mu-flat-button
        slot="actions"
        primary
        @click="addMultiCard"
        label="确定"
        :disabled="checklist.length === 0"
      />
    </mu-dialog>
  </div>
</template>

<script>
import { commonAjax, commonAjaxJson, RESTFUL_API } from "@/api/api";
import {
  testEmpty,
  getBirthdayFromIdCard,
  getAgeFromBirthday,
  getSexFromIdCard,
  testPhone
} from "@/common/js/util";
import Selector from "@/components/Selector";
import SelectRole3 from "@/components/SelectRole3";

import { HIS_CARD_TYPE, CARD_TYPE, SEX_TYPE } from "@/api/const";

export default {
  components: { Selector, SelectRole3 },
  data() {
    return {
      hospitalCode: sessionStorage.getItem("hospitalCode") || "",
      editFamily: JSON.parse( sessionStorage.editFamily || "{listBasAccountCard: []}" ),
      HIS_CARD_TYPE, SEX_TYPE,
      CARD_TYPE,
      query: {},
      redirect: "",
      form: {
        relation: 1,
        phoneNumber: "",
        cardType: "",
        cardNumber: "",
        realName: "",
        id: ""
      },
      showGuardian: false,
      guardian: JSON.parse( sessionStorage.familyPerson || "{}"),
      vcode: "",
      vcodeLabel: "获取验证码",
      vcodeDisabled: false,
      bornDate: "",
      sex: "",
      age: "",
      canDelete: true,
      listMedicalCard: [],
      mobilesList: [],
      checklist: [],
      dialogMobiles: false,
      selectCardDialog: false,
    };
  },
  watch: {
    "guardian.idcard": function(val) {
      if(this.guardian.cardtype == "1") {
        this.guardian.birthdate = getBirthdayFromIdCard(val)
        this.guardian.age = getAgeFromBirthday(getBirthdayFromIdCard(val))
      }
    },
    bornDate: function(val) {
      this.age = getAgeFromBirthday(val)
    },
    age: function(val) {
      if(Number(val) > 6) {
        this.showGuardian = false
      } else {
        this.showGuardian = true
      }
    }
  },
  computed: {
    loginDisabled() {
      if(this.showGuardian) {
        return (testEmpty(this.form.realName) ||
        testEmpty(this.form.cardNumber) ||
        testEmpty(this.bornDate) ||
        testEmpty(this.vcode) ||
        testEmpty(this.guardian.realname) ||
        testEmpty(this.guardian.idcard) ||
        testEmpty(this.guardian.mobile)
        )
      } else {
        return (
          testEmpty(this.form.realName) ||
          testEmpty(this.form.cardNumber) ||
          testEmpty(this.bornDate) ||
          testEmpty(this.vcode)
        );
      }
    },
    idCard() {
      let cardTypeText
      CARD_TYPE.forEach(v => {
        if(v.value == this.form.cardType) {
          cardTypeText = v.label
        }
      })
      return cardTypeText + "-" + this.form.cardNumber
    },
  },
  mounted() {
    let query = (this.query = this.editFamily);
    this.form.relation = query.relation;
    this.form.id = query.id;
    this.form.realName = query.realname;
    this.form.cardType = query.cardtype;
    this.form.cardNumber = query.idcard;
    this.form.phoneNumber = query.mobile;
    this.bornDate = query.birthdate;
    this.sex = query.sexcode;
  },
  // beforeRouteEnter (to, from, next) {
  //   if(from.path) {
  //     next(vm => vm.redirect = from.path)
  //   }
  //   next()
  // },
  methods: {
    go() {
      this.$router.push("/setting/family/add?action=modify");
    },
    getVcode() {
      // this.tipDialog.show = false;
      this.initTimer();
    },
    initTimer() {
      this.vcodeDisabled = true;
      let param = {
        mobile: this.form.phoneNumber
      };
      commonAjax(RESTFUL_API.confirmIdByPhone, param)
        .then(res => {
          if (res.data.code == 200) {
            this.$store.commit("UPDATE_TOAST", { message: "验证码发送成功" });
            this.timeout();
          } else {
            this.vcodeDisabled = false;
            this.$store.commit("UPDATE_TOAST", {
              message: res.data.msg || res.data.message
            });
          }
        })
        .catch(() => {
          this.$store.commit("UPDATE_TOAST", { message: "服务错误" });
          this.vcodeDisabled = false;
        });
    },
    timeout() {
      let start = 60;
      let countDown = () => {
        this.vcodeTimer = setTimeout(() => {
          this.vcodeLabel = start-- + "";
          countDown();
          if (start <= 0) {
            this.vcodeDisabled = false;
            this.vcodeLabel = "获取验证码";
            clearTimeout(this.vcodeTimer);
          }
        }, 1000);
      };
      countDown();
    },
    checkCode() {
      if (this.loginDisabled) {
        return false;
      }
      if(!this.verifyForm()) {
        return false
      }
      if (!testPhone(this.form.phoneNumber)) {
        this.$store.commit("UPDATE_TOAST", {
          message: "就诊人手机号格式有误，请检查"
        });
        return false;
      } else if (this.showGuardian && !testPhone(this.guardian.mobile)) {
        this.$store.commit("UPDATE_TOAST", {
          message: "监管人手机号格式有误，请检查"
        });
        return false;
      }
      let query = this.query;
      
      let param = {
        mobile: this.query.mobile,
        code: this.vcode
      };
      if (query.relation > 0) {
        param.fid = query.id;
      } else {
        param.uid = query.uid || query.id;
      }
      commonAjax(`${RESTFUL_API.verifyCode}`, param)
        .then(res => {
          if (res.data.code == 200) {
            this.submitForm();
          } else {
            this.$store.commit("UPDATE_TOAST", {
              message: res.data.msg || res.data.message
            });
          }
        }).catch(res => {
          this.$store.commit('UPDATE_TOAST', {message: res})
        })
    },
    selperson(val) {
      this.guardian = val
    },
    verifyForm() {
      let showGuardian = this.showGuardian
      
      if(showGuardian) {
        let guardian = this.guardian
        if(!guardian.age && guardian.cardtype == "1") {
          guardian.age = getAgeFromBirthday(getBirthdayFromIdCard(guardian.idcard))
        }
        if(guardian.age < 18) {
          this.$store.commit("UPDATE_TOAST", {
            message: "监护人须>18周岁，请重新选择"
          });
          return false;
        }
      }
      return true
    },
    mobileSelectHandle(v) {
      this.form.mobile = v.phone || this.query.mobile;
      this.listMedicalCard = v.listMedicalCard;
      this.dialogMobiles = false;
      this.addCards()
    },
    addCards() {
      const len = this.listMedicalCard.length;
      if (len === 1) {
        this.addMultiCard();
      } else if (len > 1) {
        this.selectCardDialog = true;
      } else {
        // todo
        this.$store.commit("UPDATE_TOAST", { message: "没有找到就诊卡" });
      }
    },
    addMultiCard() {
      let params = {
        // uid: this.person.uid || this.person.id,
        hospitalCode: this.hospitalCode,
        fid: this.query.uid || this.query.id
      };
      if (this.query.relation > 0) {
        params.fid = this.query.id;
      }
      if (this.listMedicalCard.length === 1) {
        params.listMedicalCard = this.listMedicalCard;
      } else {
        let temp = [];
        this.checklist.forEach(cl => {
          this.listMedicalCard.forEach(lm => {
            if (cl === lm.patientMedicalCardNumber) {
              temp.push(lm);
            }
          });
        });
        params.listMedicalCard = temp;
      }
      commonAjaxJson(RESTFUL_API.addCards, params, true).then(res => {
        if (res.data.code == 200) {
          let isMcard = false;
          if (this.listMedicalCard.length > 0) {
            let card = this.listMedicalCard[0];
            if (card.cardtype === "5") {
              isMcard = true;
            }
          }
          if (isMcard) {
            this.successDialog = true;
            return;
          }
          this.modifyHandle();
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: res.data.msg || res.data.message
          });
        }
      });
    },
    submitForm() {
      let q = this.query
      if (this.loginDisabled) {
        return false;
      }
      if(!this.verifyForm()) {
        return false
      }
      let params = {
        hospitalCode: this.hospitalCode,
        operationType: "2",
        patientMobile: this.form.phoneNumber
      };
      if (q.relation > 0) {
        params.fid = q.id;
      }
      if(this.showGuardian) {
        params.guardianName = this.guardian.realname
        params.guardianCardType = this.guardian.cardtype
        params.guardianCardNumber = this.guardian.idcard
        params.guardianMobile = this.guardian.mobile
      }
      return commonAjaxJson(RESTFUL_API.getHisPhone, params, true).then(res => {
        if (res.data.code == 200) {
          if (res.data.data && res.data.data.length > 1) {
            this.dialogMobiles = true;
            this.mobilesList = res.data.data;
          } else if (res.data.data && res.data.data.length == 1 && res.data.data[0].phone) {
            let d = res.data.data[0];
            this.form.mobile = d.phone
            this.listMedicalCard = d.listMedicalCard;
            this.addCards()
          }
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: res.data.message
          });
        }
      })
    },
    modifyHandle() {
      this.$store.commit("UPDATE_TOAST", {
        message: "操作成功",
        fn: () => this.$router.go(-1)
      });
    },
    handleCardChange(val) {
      this.form.cardType = val;
    },
    handleRelationChange(val) {
      this.form.relation = val;
    },
    handleSexChange(val) {
      this.sex = val;
    },
    showDatePicker (){
      this.$picker.show({
        date: this.bornDate,
        succeed: (e) => {
          this.bornDate = e
        }
      })
    }
  },
  destroyed() {}
};
</script>
<style lang="less" scope>
.warning-tips {
  width: 100%;
  height: 30px;
  line-height: 30px;
  text-align: center;
  font-size: 14px;
  color: #ff6600;
  background: #fffdce;
}
.zxjd {
  width: 18px;
  height: 18px;
  margin-right: 5px;
  vertical-align: middle;
}
</style>
